package com.booter.ws.config.response;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author lcw
 * @date 2023/8/16 18:20
 */
@Slf4j
public class HttpResponseOutStreamCopier extends HttpServletResponseWrapper {

    private ByteArrayOutputStream os;
    private PrintWriter writer;


    public HttpResponseOutStreamCopier(HttpServletResponse response) {
        super(response);
        os = new ByteArrayOutputStream();
        writer = new PrintWriter(os);
    }

    @Override
    public PrintWriter getWriter() {
        return writer;
    }

    @Override
    public ServletOutputStream getOutputStream() {
        return new ServletOutputStream() {
            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setWriteListener(WriteListener listener) {

            }

            @Override
            public void write(int b) {
                os.write(b);
            }
        };
    }

    public void flush() {
        try {
            writer.flush();
            writer.close();
            os.flush();
            os.close();
        } catch (IOException ex) {
            log.error("操作响应流异常", ex);
        }
    }

    public ByteArrayOutputStream getByteArrayOutputStream() {
        return os;
    }


    public String getTextContent() {
        flush();
        return os.toString();
    }

    public byte[] getBody() {
        return os.toByteArray();
    }
}